import { preferences } from '@kit.ArkData'; // 导入模块

class PreferenceUtil{
    private preferenceList:Map<string,preferences.Preferences> = new Map()
    // 加载prefercence
    async loadPreference(context,name:string) : Promise<void>{
        try {
            //获取Preferences实例
            const dataPreferences:preferences.Preferences = await preferences.getPreferencesSync(context, {name})
            this.preferenceList.set(name,dataPreferences)
            console.log('preferenceTAG',`加载Preference[${name}]成功`)
        }catch (error){
            console.log('preferenceTAG',`加载Preference[${name}]失败`,JSON.stringify(error))
        }
    }
    // 保存数据
    async  putPreferenceValue(name:string,key:string,value:preferences.ValueType) : Promise<void>{
        if(!this.preferenceList.has(name)){
            console.log('preferenceTAG',`Preference[${name}]尚未初始化！`)
            return
        }
        try {
            const pref = this.preferenceList.get(name)
            await pref?.put(key,value)
            await pref?.flush()
            console.log('preferenceTAG',`保存Preference[${name}.${key}=${value}]成功！`)
        }catch (error){
            console.log('preferenceTAG',`保存Preference[${name}]失败`,JSON.stringify(error))
        }
    }
    // 读到数据
    async  getPreferenceValue(name:string, key:string, defalutValue:preferences.ValueType) : Promise<preferences.ValueType>{
        if(!this.preferenceList.has(name)){
            console.log('preferenceTAG',`Preference[${name}]尚未初始化！`)
            return
        }
        try {
            const pref = this.preferenceList.get(name)
            const value = await pref?.get(key,defalutValue)
            return value
        }catch (error){
            console.log('preferenceTAG',`读取Preference[${name}.${key}]失败`,JSON.stringify(error))
        }
    }
}

export default new PreferenceUtil()